<?php
namespace app\home\controller;

use \app\common\controller\Base;
use \app\common\model\User;
use \think\Loader;
use \think\Session;
use \think\Log;
use \thans\Ret;

class Login extends Base
{
    public function index()
    {
        return $this->fetch();
    }

    public function doLogin()
    {
        
        $user = Loader::model('User');
        $post_data = $user->getPost();
        if($post_data) {
            $check_form = $user->checkForm($post_data,'login');
            if($check_form) {
               return $this->ret->setCode(1)->setMsg($check_form)->toJson();
            }
            if(okay_ismobile($post_data['user_name'])){
                $user_info = $user->getUserBy('mobile',$post_data['user_name']);
            }elseif (okay_isemail($post_data['user_name'])) {
                $user_info = $user->getUserBy('email',$post_data['user_name']);
            }else{
                $user_info = $user->getUserByName($post_data['user_name']);
            }
            if(!$user_info) {
                return $this->ret->setCode(1)->setMsg('登陆失败,用户不存在')->toJson();
            } else {
                if($user_info['user_type']){
                    return $this->ret->setCode(0)->setMsg('非管理员禁止从此接口登录')->setUrl(url('/main'))->toJson();
                }
                $confirm_pwd = inge_encryption_pwd($post_data['user_pwd'], $user_info['user_pwd_rand']);
                if($confirm_pwd == $user_info['user_pwd']) {
                    /**
                     * 先判断密码是否正确
                     */
                    unset($user_info['user_pwd']);
                    unset($user_info['user_pwd_rand']);
                    $user->checkUserStatus($user_info['user_id']);
                    $user->updateLoginInfo($post_data['user_name']);
                    Session::set('u_info', $user_info);
                    Session::set('u_id', $user_info['user_id']);
                    $url = url('/main');
                    return $this->ret->setCode(0)->setMsg('登陆成功')->setUrl($url)->toJson();
                }else {
                    return $this->ret->setCode(1)->setMsg('登陆失败,密码错误')->toJson();
                }
            }
        }else{
            return $this->ret->setCode(1)->setMsg('非法操作')->setReload()->toJson();
        }
    }

    public function logOut()
    {
        /**
         * 退出登录删除全部session
         */
        session(null);
        $this->success('退出成功', url('home/Login/index'));
        
    }
}
